package com.iotechn.unimall.admin.api.purchaseWarehouseOrder;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.biz.service.config.ConfigBizService;
import com.iotechn.unimall.biz.service.goods.GoodsBizService;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.core.util.MoneyUtils;
import com.iotechn.unimall.data.domain.*;
import com.iotechn.unimall.data.dto.AdminDTO;
import com.iotechn.unimall.data.dto.warehouse.PurchaseWarehouseOperLogDTO;
import com.iotechn.unimall.data.dto.warehouse.PurchaseWarehouseOrderDTO;
import com.iotechn.unimall.data.dto.warehouse.PurchaseWarehouseOrderGoodsDTO;
import com.iotechn.unimall.data.mapper.*;
import com.iotechn.unimall.data.model.Page;
import com.iotechn.unimall.data.util.SessionUtil;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class PurchaseWarehouseOrderServiceImpl implements PurchaseWarehouseOrderService {
    @Autowired
    private PurchaseWarehouseOrderMapper purchaseWarehouseOrderMapper;
    @Autowired
    private PurchaseWarehouseOrderGoodsMapper purchaseWarehouseOrderGoodsMapper;
    @Autowired
    private PurchaseWarehouseOperLogMapper purchaseWarehouseOperLogMapper;
    @Autowired
    private PurchaseGoodsPriceLogMapper purchaseGoodsPriceLogMapper;
    @Autowired
    private WarehouseGoodsMapper warehouseGoodsMapper;
    @Autowired
    private WarehouseOperLogMapper warehouseOperLogMapper;
    @Autowired
    private FinancePayableMapper financePayableMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private GoodsBizService goodsBizService;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ConfigBizService configBizService;
    @Autowired
    private SkuMapper skuMapper;

    @Override
    public Page<PurchaseWarehouseOrderDO> list(Integer page, Integer limit, Long adminId, String warehouseOrderNo, String skuSearch,
                                               String insertStartTime, String insertEndTime,
                                               String warehouseOrderState) throws ServiceException {
        Wrapper<PurchaseWarehouseOrderDO> wrapper = new EntityWrapper<PurchaseWarehouseOrderDO>();

        if (!StringUtils.isEmpty(warehouseOrderNo)) {
            wrapper.like("warehouse_order_no", warehouseOrderNo);
        }
        if (!StringUtils.isEmpty(warehouseOrderState)) {
            wrapper.eq("warehouse_order_state", warehouseOrderState);
        }
        //时间范围搜索
        if (!StringUtils.isEmpty(insertStartTime)) {
            wrapper.gt("gmt_create", insertStartTime);
        }
        if (!StringUtils.isEmpty(insertEndTime)) {
            wrapper.le("gmt_create", insertEndTime);
        }
        List<Long> orderIds = new LinkedList<>();
        if (!StringUtils.isEmpty(skuSearch)) {
            List<PurchaseWarehouseOrderGoodsDO> orderSkus = purchaseWarehouseOrderGoodsMapper.selectList(new EntityWrapper<PurchaseWarehouseOrderGoodsDO>()
                    .like("goods_bar_code", skuSearch).or().like("spu_name", skuSearch).or().like("sku_name", skuSearch));

            if (CollectionUtils.isEmpty(orderSkus)) {
                return new Page<>(new ArrayList<>(), page, limit, 0L);
            }
            orderIds = orderSkus.stream().map(PurchaseWarehouseOrderGoodsDO::getWarehouseOrderId).distinct().collect(Collectors.toList());

            wrapper.in(!CollectionUtils.isEmpty(orderIds), "id", orderIds);

        }
        wrapper.orderBy("id", false);
        Integer count = purchaseWarehouseOrderMapper.selectCount(wrapper);
        List<PurchaseWarehouseOrderDO> purchaseWarehouseOrderDOS = purchaseWarehouseOrderMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        purchaseWarehouseOrderDOS.forEach(item -> {
            List<PurchaseWarehouseOrderGoodsDO> skus = purchaseWarehouseOrderGoodsMapper.selectList(new EntityWrapper<PurchaseWarehouseOrderGoodsDO>()
                    .eq("warehouse_order_id", item.getId()));
            item.setSkus(skus);
        });
        return new Page<>(purchaseWarehouseOrderDOS, page, limit, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(PurchaseWarehouseOrderDTO purchaseWarehouseOrderDTO, Long adminId) throws ServiceException {
        //参数校验
        if (CollectionUtils.isEmpty(purchaseWarehouseOrderDTO.getPurchaseWarehouseOrderGoodsDTOS())) {
            //未选择入库商品
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        BigDecimal ratio = new BigDecimal(Float.toString(100.00f));
        Date now = new Date();
        PurchaseWarehouseOrderDO purchaseWarehouseOrderDO = new PurchaseWarehouseOrderDO();
        BeanUtils.copyProperties(purchaseWarehouseOrderDTO, purchaseWarehouseOrderDO);
        purchaseWarehouseOrderDO.setGmtUpdate(now);
        purchaseWarehouseOrderDO.setGmtCreate(now);
        purchaseWarehouseOrderDO.setAdminId(adminId);
        purchaseWarehouseOrderDO.setWarehouseOrderState(0);//待入库
        purchaseWarehouseOrderDO.setPOrderId(0L);//采购单默认为0,后期改
        purchaseWarehouseOrderDO.setWarehouseOrderNo("RK" + System.currentTimeMillis());//入库单编号自动生成
        purchaseWarehouseOrderDO.setWarehouseOrderPaymentCode("");//支付方式待定
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsAmount(ratio.multiply(new BigDecimal(Float.toString(purchaseWarehouseOrderDTO.getTotalPrice()))).longValue());
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsCount(purchaseWarehouseOrderDTO.getTotal());
        purchaseWarehouseOrderDO.setWarehouseOrderConpon(purchaseWarehouseOrderDTO.getWarehouseOrderConpon() == null ? 0 : (int) (purchaseWarehouseOrderDTO.getWarehouseOrderConpon() * 100));
        Float warehouseOrderAmount = ratio.multiply(new BigDecimal(Float.toString(purchaseWarehouseOrderDTO.getTotalPrice()))).floatValue() - (purchaseWarehouseOrderDTO.getWarehouseOrderConpon() == null ? 0 : ratio.multiply(new BigDecimal(Float.toString(purchaseWarehouseOrderDTO.getWarehouseOrderConpon()))).floatValue());
        purchaseWarehouseOrderDO.setWarehouseOrderAmount(new BigDecimal(Float.toString(warehouseOrderAmount)).longValue());
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsAmount((new BigDecimal(Float.toString(warehouseOrderAmount))).longValue());

//        if (purchaseWarehouseOrderDO.getWarehouseOrderState() == 1) {//已入库
//            purchaseWarehouseOrderDO.setWarehouseOrderInsertTime(now);
//        }
        //操作人真实姓名
        AdminDTO adminDTO = SessionUtil.getAdmin();
        if (adminDTO != null) {
            purchaseWarehouseOrderDO.setAdminRealname(adminDTO.getRealname());
        }
        if (purchaseWarehouseOrderMapper.insert(purchaseWarehouseOrderDO) > 0) {
            //插入入库商品表
            for (PurchaseWarehouseOrderGoodsDTO purchaseWarehouseOrderGoodsDTO : purchaseWarehouseOrderDTO.getPurchaseWarehouseOrderGoodsDTOS()) {
                PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO = new PurchaseWarehouseOrderGoodsDO();
                BeanUtils.copyProperties(purchaseWarehouseOrderGoodsDTO, purchaseWarehouseOrderGoodsDO);
                purchaseWarehouseOrderGoodsDO.setWarehouseOrderId(purchaseWarehouseOrderDO.getId());
                purchaseWarehouseOrderGoodsDO.setWarehouseId(purchaseWarehouseOrderDO.getWarehouseId());
                purchaseWarehouseOrderGoodsDO.setGoodsNo(purchaseWarehouseOrderGoodsDTO.getBarCode());// 商品编码为条形码
                purchaseWarehouseOrderGoodsDO.setGoodsBarCode(purchaseWarehouseOrderGoodsDTO.getBarCode());
                purchaseWarehouseOrderGoodsDO.setSkuId(purchaseWarehouseOrderGoodsDTO.getSkuId());
                purchaseWarehouseOrderGoodsDO.setGoodsImg(purchaseWarehouseOrderGoodsDTO.getImg());
                purchaseWarehouseOrderGoodsDO.setGoodsUnit(purchaseWarehouseOrderGoodsDTO.getUnit());
                Long averPrice = 0l;
                List<WarehouseGoodsDO> warehouseGoodsDOS = warehouseGoodsMapper.selectList(new EntityWrapper<WarehouseGoodsDO>().eq("sku_id", purchaseWarehouseOrderGoodsDTO.getSkuId()).eq("warehouse_id", purchaseWarehouseOrderDTO.getWarehouseId()));
                WarehouseGoodsDO warehouseGoodsDO=new WarehouseGoodsDO();
                //当前平均价
                Float averPriceF = 0f;
                //当前库存
                Float warehouseSkuNum = 0f;
                if(warehouseGoodsDOS != null && warehouseGoodsDOS.size() > 0){
                    warehouseGoodsDO =warehouseGoodsDOS.get(0);
                }
                if(warehouseGoodsDO.getPrice() == null || "".equals(warehouseGoodsDO.getPrice())){
                    averPrice= MoneyUtils.mul(MoneyUtils.div(purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsAmount().doubleValue(),purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsBuyNum().doubleValue(),3),100d).longValue();
                }else{
                    averPriceF = warehouseGoodsDO.getPrice().floatValue();
                    warehouseSkuNum = warehouseGoodsDO.getWarehouseSkuStock();
                    //此次入库商品总价
                    Float goodsTotalPrice = MoneyUtils.mul(purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsAmount().doubleValue(),100d).floatValue();
                    //计算总数
                    Float avgNum = MoneyUtils.add(warehouseSkuNum.doubleValue(),purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsBuyNum().doubleValue()).floatValue();

                    Float avgPrice =MoneyUtils.add(MoneyUtils.mul(averPriceF.doubleValue(),warehouseSkuNum.doubleValue()),goodsTotalPrice.doubleValue()).floatValue();

                    averPrice = MoneyUtils.div(avgPrice.doubleValue(), avgNum.doubleValue(), 3).longValue();
                }


                purchaseWarehouseOrderGoodsDO.setGoodsAverPrice(averPrice);//入库时如果没有平均价格说明第一次入库，平均价格为当前价格
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsPrice((long) (Float.valueOf(purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsPrice()) * 100));
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsAmount((long) (Float.valueOf(purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsPrice()) * Float.valueOf(purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsBuyNum())) * 100);
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsAmount((long) (purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsAmount() * 100));
                purchaseWarehouseOrderGoodsDO.setGoodsPreAverPrice(warehouseGoodsDO.getPrice());
                purchaseWarehouseOrderGoodsDO.setGmtCreate(now);
                purchaseWarehouseOrderGoodsDO.setGmtUpdate(now);
                purchaseWarehouseOrderGoodsMapper.insert(purchaseWarehouseOrderGoodsDO);
            }
            //插入操作表
            //操作人真实姓名
            if (adminDTO != null) {
                purchaseWarehouseOrderDO.setAdminRealname(adminDTO.getRealname());
                insertPurchaseWarehouseOperLog(purchaseWarehouseOrderDO, adminDTO);
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(PurchaseWarehouseOrderDTO purchaseWarehouseOrderDTO, Long adminId) throws ServiceException {
        Long id = purchaseWarehouseOrderDTO.getId();
        if (id == null) {
            return "fail";
        }

        BigDecimal ratio = new BigDecimal(Float.toString(100.00f));
        Date now = new Date();
        PurchaseWarehouseOrderDO purchaseWarehouseOrderDO = new PurchaseWarehouseOrderDO();
        BeanUtils.copyProperties(purchaseWarehouseOrderDTO, purchaseWarehouseOrderDO);
        purchaseWarehouseOrderDO.setGmtUpdate(now);
        purchaseWarehouseOrderDO.setAdminId(adminId);
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsAmount(ratio.multiply(new BigDecimal(Float.toString(purchaseWarehouseOrderDTO.getTotalPrice()))).longValue());
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsCount(purchaseWarehouseOrderDTO.getTotal());
        purchaseWarehouseOrderDO.setWarehouseOrderConpon(purchaseWarehouseOrderDTO.getWarehouseOrderConpon() == null ? 0 : (int) (purchaseWarehouseOrderDTO.getWarehouseOrderConpon() * 100));
        Float warehouseOrderAmount = ratio.multiply(new BigDecimal(Float.toString(purchaseWarehouseOrderDTO.getTotalPrice()))).floatValue() - (purchaseWarehouseOrderDTO.getWarehouseOrderConpon() == null ? 0 : ratio.multiply(new BigDecimal(Float.toString(purchaseWarehouseOrderDTO.getWarehouseOrderConpon()))).floatValue());
        purchaseWarehouseOrderDO.setWarehouseOrderAmount(new BigDecimal(Float.toString(warehouseOrderAmount)).longValue());
        purchaseWarehouseOrderDO.setWarehouseOrderGoodsAmount((new BigDecimal(Float.toString(warehouseOrderAmount))).longValue());
        //删除入库单-商品数据
        purchaseWarehouseOrderGoodsMapper.delete(new EntityWrapper<PurchaseWarehouseOrderGoodsDO>()
                .eq("warehouse_order_id", purchaseWarehouseOrderDTO.getId())
                .eq("warehouse_id", purchaseWarehouseOrderDTO.getWarehouseId()));
        purchaseWarehouseOrderDO.setGmtUpdate(now);
        if (purchaseWarehouseOrderMapper.updateById(purchaseWarehouseOrderDO) > 0) {
            //更新时先删除入库单-商品
            for (PurchaseWarehouseOrderGoodsDTO purchaseWarehouseOrderGoodsDTO : purchaseWarehouseOrderDTO.getPurchaseWarehouseOrderGoodsDTOS()) {
                PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO = new PurchaseWarehouseOrderGoodsDO();
                BeanUtils.copyProperties(purchaseWarehouseOrderGoodsDTO, purchaseWarehouseOrderGoodsDO);
                purchaseWarehouseOrderGoodsDO.setWarehouseOrderId(purchaseWarehouseOrderDO.getId());
                purchaseWarehouseOrderGoodsDO.setWarehouseId(purchaseWarehouseOrderDO.getWarehouseId());
                purchaseWarehouseOrderGoodsDO.setGoodsNo(purchaseWarehouseOrderGoodsDTO.getBarCode());// 商品编码为条形码
                purchaseWarehouseOrderGoodsDO.setGoodsBarCode(purchaseWarehouseOrderGoodsDTO.getBarCode());// 商品编码为条形码
                purchaseWarehouseOrderGoodsDO.setGoodsImg(purchaseWarehouseOrderGoodsDTO.getImg());
                purchaseWarehouseOrderGoodsDO.setGoodsUnit(purchaseWarehouseOrderGoodsDTO.getUnit());
                purchaseWarehouseOrderGoodsDO.setSkuId(purchaseWarehouseOrderGoodsDTO.getSkuId());
                purchaseWarehouseOrderGoodsDO.setGoodsAverPrice(purchaseWarehouseOrderGoodsDTO.getAverPrice() == null || "".equals(purchaseWarehouseOrderGoodsDTO.getAverPrice()) ? (long) (Float.valueOf(purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsPrice()) * 100) : purchaseWarehouseOrderGoodsDTO.getAverPrice().longValue());//入库时如果没有平均价格说明第一次入库，平均价格为当前价格
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsPrice(ratio.multiply(new BigDecimal(Float.toString(purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsPrice()))).longValue());
                purchaseWarehouseOrderGoodsDO.setWarehouseGoodsAmount(ratio.multiply(new BigDecimal(Float.toString(purchaseWarehouseOrderGoodsDTO.getWarehouseGoodsAmount()))).longValue());
                purchaseWarehouseOrderGoodsDO.setGmtCreate(now);
                purchaseWarehouseOrderGoodsDO.setGmtUpdate(now);
                purchaseWarehouseOrderGoodsMapper.insert(purchaseWarehouseOrderGoodsDO);
            }
            //操作人真实姓名
            AdminDTO adminDTO = SessionUtil.getAdmin();
            if (adminDTO != null) {
                purchaseWarehouseOrderDO.setAdminRealname(adminDTO.getRealname());
                insertPurchaseWarehouseOperLog(purchaseWarehouseOrderDO, adminDTO);
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long id, Long adminId) throws ServiceException {
        if (purchaseWarehouseOrderMapper.deleteById(id) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);

    }

    @Override
    public PurchaseWarehouseOrderDTO detail(Long id, Long adminId) throws ServiceException {
        PurchaseWarehouseOrderDO purchaseWarehouseOrderDO = purchaseWarehouseOrderMapper.selectById(id);
        PurchaseWarehouseOrderDTO purchaseWarehouseOrderDTO = new PurchaseWarehouseOrderDTO();
        BeanUtils.copyProperties(purchaseWarehouseOrderDO, purchaseWarehouseOrderDTO);

        //价格金额处理
        purchaseWarehouseOrderDTO.setWarehouseOrderConpon(purchaseWarehouseOrderDO.getWarehouseOrderConpon() == null ? 0 : purchaseWarehouseOrderDO.getWarehouseOrderConpon() / 100.00f);
        purchaseWarehouseOrderDTO.setWarehouseOrderAmount((Float.valueOf(purchaseWarehouseOrderDO.getWarehouseOrderAmount()) / 100));
        purchaseWarehouseOrderDTO.setWarehouseOrderGoodsAmount(Float.valueOf(purchaseWarehouseOrderDO.getWarehouseOrderGoodsAmount()) / 100);
        WarehouseDO warehouseDO = warehouseMapper.selectById(purchaseWarehouseOrderDO.getWarehouseId());
        if (warehouseDO != null) {
            purchaseWarehouseOrderDTO.setWarehouseName(warehouseDO.getWarehouseName());
        }
        SupplierDO supplierDO = supplierMapper.selectById(purchaseWarehouseOrderDO.getSupplierId());
        if (supplierDO != null) {
            purchaseWarehouseOrderDTO.setSupplierName(supplierDO.getSupplierName());
        }
//通过入库单获取商品
        List<PurchaseWarehouseOrderGoodsDTO> purchaseWarehouseOrderGoodsDTOS = purchaseWarehouseOrderGoodsMapper.querySkusByPara(null, id, null, null, null);
        //价格处理
        purchaseWarehouseOrderGoodsDTOS.stream().map(i -> {
            i.setWarehouseGoodsPrice((Float.valueOf(i.getWarehouseGoodsPrice()) / 100));
            i.setWarehouseGoodsAmount((Float.valueOf(i.getWarehouseGoodsAmount()) / 100));
            return i;
        }).collect(Collectors.toList());
        purchaseWarehouseOrderDTO.setPurchaseWarehouseOrderGoodsDTOS(purchaseWarehouseOrderGoodsDTOS);
        //操作日志
        List<PurchaseWarehouseOperLogDTO> purchaseWarehouseOperLogDTOS = purchaseWarehouseOperLogMapper.listWarehouseOrderLogsByPara(id);
        purchaseWarehouseOrderDTO.setPurchaseWarehouseOperLogDTOS(purchaseWarehouseOperLogDTOS);
        return purchaseWarehouseOrderDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String audit(Long warehouseOrderId, Integer warehouseOrderState, String auditComment, Long adminId) throws ServiceException {
        if (warehouseOrderId == null || "".equals(warehouseOrderId)) {
            return "fail";
        }
        PurchaseWarehouseOrderDO purchaseWarehouseOrderDO = purchaseWarehouseOrderMapper.selectById(warehouseOrderId);
        if (purchaseWarehouseOrderDO == null) {
            return "fail";
        }
        purchaseWarehouseOrderDO.setWarehouseOrderState(warehouseOrderState);
        purchaseWarehouseOrderDO.setWarehouseOrderAuditComment(auditComment);
        Date now = new Date();
        AdminDTO adminDTO = SessionUtil.getAdmin();
        boolean isPassed = purchaseWarehouseOrderDO.getWarehouseOrderState().intValue() == 1;
        if (adminDTO != null && isPassed) {
            purchaseWarehouseOrderDO.setWarehouseOrderConfirmUserId(adminId);
            purchaseWarehouseOrderDO.setWarehouseOrderConfirmRealname(adminDTO.getRealname());
            purchaseWarehouseOrderDO.setWarehouseOrderInsertTime(now);
            if (purchaseWarehouseOrderDO.getWarehouseOrderAuditUserId() == null) {
                purchaseWarehouseOrderDO.setWarehouseOrderAuditUserId(adminId);
                purchaseWarehouseOrderDO.setWarehouseOrderAuditTime(now);
                purchaseWarehouseOrderDO.setWarehouseOrderAuditRealname(adminDTO.getRealname());
            }
        }
        if (purchaseWarehouseOrderMapper.updateById(purchaseWarehouseOrderDO) > 0) {
            if (isPassed) {//通过
                WarehouseDO warehouseDO = warehouseMapper.selectById(purchaseWarehouseOrderDO.getWarehouseId());
                List<PurchaseWarehouseOrderGoodsDO> purchaseWarehouseOrderGoodsDOS = purchaseWarehouseOrderGoodsMapper.selectList(new EntityWrapper<PurchaseWarehouseOrderGoodsDO>()
                        .eq("warehouse_order_id", purchaseWarehouseOrderDO.getId())
                        .eq("warehouse_id", purchaseWarehouseOrderDO.getWarehouseId()));
//通用仓库预警
                Float alarm = configBizService.getCommonGoodsAlarm();
                for (PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO : purchaseWarehouseOrderGoodsDOS) {
                    //更新库存商品数量
                    List<WarehouseGoodsDO> warehouseGoodsDOS = warehouseGoodsMapper.selectList(new EntityWrapper<WarehouseGoodsDO>()
                            .eq("warehouse_id", purchaseWarehouseOrderDO.getWarehouseId())
                            .eq("sku_id", purchaseWarehouseOrderGoodsDO.getSkuId()));
                    WarehouseGoodsDO warehouseGoodsDO = null;
                    WarehouseGoodsDO origWarehouseGoodsDO = null;
                    Float changeSkuStock = purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum();
                    Float totalSkuStock = 0.00f;
                    if (!CollectionUtils.isEmpty(warehouseGoodsDOS)) {
                        warehouseGoodsDO = warehouseGoodsDOS.get(0);
                        origWarehouseGoodsDO = new WarehouseGoodsDO();
                        BeanUtils.copyProperties(warehouseGoodsDO,origWarehouseGoodsDO);
                        if (warehouseGoodsDO != null) {
                            Float warehouseSkuStock = warehouseGoodsDO.getWarehouseSkuStock();
                            warehouseSkuStock = warehouseSkuStock == null || "".equals(warehouseGoodsDO) ? 0 : warehouseSkuStock;
                            totalSkuStock = warehouseSkuStock + changeSkuStock;
                            warehouseGoodsDO.setWarehouseSkuStock(totalSkuStock);
                            warehouseGoodsDO.setSpuId(purchaseWarehouseOrderGoodsDO.getGoodsId());
                            warehouseGoodsDO.setAllprice((long) (purchaseWarehouseOrderGoodsDO.getWarehouseGoodsPrice() * purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum()) + warehouseGoodsDO.getAllprice());
                            warehouseGoodsDO.setPrice(purchaseWarehouseOrderGoodsDO.getGoodsAverPrice());
                            warehouseGoodsDO.setTitle(purchaseWarehouseOrderGoodsDO.getSpuName() + " " + purchaseWarehouseOrderGoodsDO.getSkuName());
                            warehouseGoodsDO.setSkuId(purchaseWarehouseOrderGoodsDO.getSkuId());
                            warehouseGoodsDO.setGmtUpdate(now);
                            Float goodsHistoryAmount = warehouseGoodsDO.getGoodsHistoryAmount() == null ? 0L : warehouseGoodsDO.getGoodsHistoryAmount();
                            warehouseGoodsDO.setGoodsHistoryAmount(goodsHistoryAmount + changeSkuStock);
                            warehouseGoodsDO.setWarehouseName(warehouseDO.getWarehouseName());
                            warehouseGoodsDO.setImg(purchaseWarehouseOrderGoodsDO.getGoodsImg());
//                            if (warehouseGoodsDO.getAlarm() != null && !warehouseGoodsDO.getAlarm().equals(0.0f)) {
//                                warehouseGoodsDO.setAlarm(alarm);
//                            }
                            warehouseGoodsMapper.updateById(warehouseGoodsDO);
                        }
                    } else {
                        warehouseGoodsDO = new WarehouseGoodsDO();
                        warehouseGoodsDO.setGmtCreate(now);
                        warehouseGoodsDO.setGmtUpdate(now);
                        warehouseGoodsDO.setAdminId(adminId);
                        warehouseGoodsDO.setWarehouseName(warehouseDO.getWarehouseName());
                        warehouseGoodsDO.setWarehouseSkuStock(purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum());
                        warehouseGoodsDO.setWarehouseId(purchaseWarehouseOrderDO.getWarehouseId());
                        warehouseGoodsDO.setSkuId(purchaseWarehouseOrderGoodsDO.getSkuId());
                        totalSkuStock = purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum();
                        warehouseGoodsDO.setPrice(purchaseWarehouseOrderGoodsDO.getGoodsAverPrice());
                        warehouseGoodsDO.setSpuId(purchaseWarehouseOrderGoodsDO.getGoodsId());
                        warehouseGoodsDO.setGoodsHistoryAmount(totalSkuStock);
                        warehouseGoodsDO.setSkuBarCode(purchaseWarehouseOrderGoodsDO.getGoodsBarCode());
                        warehouseGoodsDO.setUnit(purchaseWarehouseOrderGoodsDO.getGoodsUnit());
                        warehouseGoodsDO.setImg(purchaseWarehouseOrderGoodsDO.getGoodsImg());
                        warehouseGoodsDO.setGoodsHistoryAmount(totalSkuStock);
                        warehouseGoodsDO.setTitle(purchaseWarehouseOrderGoodsDO.getSpuName() + " " + purchaseWarehouseOrderGoodsDO.getSkuName());
                        // warehouseGoodsDO.setAllprice((long) (purchaseWarehouseOrderGoodsDO.getWarehouseGoodsPrice() * purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum()));
                        warehouseGoodsDO.setAllprice(purchaseWarehouseOrderGoodsDO.getWarehouseGoodsAmount());
                        warehouseGoodsDO.setAlarm(alarm == null ? 0f : alarm);
                        warehouseGoodsMapper.insert(warehouseGoodsDO);
                    }
                    //更新仓库-商品操作
                    WarehouseOperLogDO warehouseOperLogDO = new WarehouseOperLogDO();
                    warehouseOperLogDO.setGmtCreate(now);
                    warehouseOperLogDO.setGmtUpdate(now);
                    warehouseOperLogDO.setChangeSkuStock(purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum());
                    warehouseOperLogDO.setAdminId(adminId);
                    warehouseOperLogDO.setSkuId(purchaseWarehouseOrderGoodsDO.getSkuId());
                    warehouseOperLogDO.setGmtUpdate(now);
                    warehouseOperLogDO.setType(1);//1代表入库
                    warehouseOperLogDO.setChangeSkuStock(changeSkuStock);
                    warehouseOperLogDO.setWarehouseSkuStock(totalSkuStock);
                    warehouseOperLogDO.setWarehouseId(purchaseWarehouseOrderGoodsDO.getWarehouseId());
                    warehouseOperLogDO.setWarehouseName(warehouseDO.getWarehouseName());
                    warehouseOperLogDO.setSkuNo(purchaseWarehouseOrderGoodsDO.getGoodsBarCode());
                    warehouseOperLogDO.setOrderNo(purchaseWarehouseOrderDO.getWarehouseOrderNo());
                    warehouseOperLogDO.setOrderId(purchaseWarehouseOrderGoodsDO.getWarehouseOrderId());
                    warehouseOperLogDO.setAdminName(adminDTO.getRealname());
                    warehouseOperLogDO.setSkuName(purchaseWarehouseOrderGoodsDO.getSkuName());
                    warehouseOperLogDO.setSkuId(purchaseWarehouseOrderGoodsDO.getSkuId());
                    warehouseOperLogDO.setSpuId(purchaseWarehouseOrderGoodsDO.getGoodsId());
                    warehouseOperLogDO.setSpuName(purchaseWarehouseOrderGoodsDO.getSpuName());
                    //补充字段
                    warehouseOperLogDO.setOrigSkuStock(0f);
                    warehouseOperLogDO.setOrigAvgPrice(0);
                    if(origWarehouseGoodsDO != null){
                        if(origWarehouseGoodsDO.getWarehouseSkuStock() != null){
                            warehouseOperLogDO.setOrigSkuStock(origWarehouseGoodsDO.getWarehouseSkuStock());
                        }
                    }
                    if(origWarehouseGoodsDO != null){
                        if(origWarehouseGoodsDO.getPrice() != null){
                            warehouseOperLogDO.setOrigAvgPrice(origWarehouseGoodsDO.getPrice().intValue());
                        }
                    }
                    warehouseOperLogDO.setCurrAvgPrice(warehouseGoodsDO.getPrice().intValue());
                    warehouseOperLogMapper.insert(warehouseOperLogDO);
                    //总库变化
              //      goodsBizService.updateGoodsStockByPara(purchaseWarehouseOrderGoodsDO.getSkuId(), purchaseWarehouseOrderGoodsDO.getGoodsBarCode(), GoodsEntryType.PURCHASE.getCode(), purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum());
                }

                //插入应付记录
                FinancePayableDO financePayableDO = new FinancePayableDO();
                financePayableDO.setGmtUpdate(now);
                financePayableDO.setAdminId(adminId);
                financePayableDO.setAdminName(adminDTO.getRealname());
                financePayableDO.setFinishAmount(0);
                financePayableDO.setAddTime(purchaseWarehouseOrderDO.getWarehouseOrderAuditTime());
                financePayableDO.setPaymentCode("");
                financePayableDO.setSupplierId(purchaseWarehouseOrderDO.getSupplierId());
                financePayableDO.setPaymentYouhuiAmount(purchaseWarehouseOrderDO.getWarehouseOrderConpon());
                financePayableDO.setSupplierName(purchaseWarehouseOrderDO.getSupplierName());
                financePayableDO.setWarehouseOrderId(purchaseWarehouseOrderDO.getId());
                financePayableDO.setWarehouseOrderNo(purchaseWarehouseOrderDO.getWarehouseOrderNo());
                financePayableDO.setPaymentAllAmount(purchaseWarehouseOrderDO.getWarehouseOrderGoodsAmount().intValue());
                financePayableDO.setPaymentAmount(purchaseWarehouseOrderDO.getWarehouseOrderAmount().intValue());
                financePayableDO.setWarehouseId(purchaseWarehouseOrderDO.getWarehouseId());
                financePayableMapper.insert(financePayableDO);


            }
            //插入操作表
            //操作人真实姓名
            if (adminDTO != null) {
                insertPurchaseWarehouseOperLog(purchaseWarehouseOrderDO, adminDTO);
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);


    }


    @Override
    public String auditBAK(Long warehouseOrderId, Integer warehouseOrderState, String auditComment, Long adminId) throws ServiceException {
        if (warehouseOrderId == null || "".equals(warehouseOrderId)) {
            return "fail";
        }
        PurchaseWarehouseOrderDO purchaseWarehouseOrderDO = purchaseWarehouseOrderMapper.selectById(warehouseOrderId);
        if (purchaseWarehouseOrderDO == null) {
            return "fail";
        }
        purchaseWarehouseOrderDO.setWarehouseOrderState(warehouseOrderState);
        purchaseWarehouseOrderDO.setWarehouseOrderAuditComment(auditComment);
        Date now = new Date();
        AdminDTO adminDTO = SessionUtil.getAdmin();
        boolean isPassed = purchaseWarehouseOrderDO.getWarehouseOrderState() == 1;
        if (adminDTO != null && isPassed) {
            purchaseWarehouseOrderDO.setWarehouseOrderConfirmUserId(adminId);
            purchaseWarehouseOrderDO.setWarehouseOrderConfirmRealname(adminDTO.getRealname());
            purchaseWarehouseOrderDO.setWarehouseOrderInsertTime(now);
            if (purchaseWarehouseOrderDO.getWarehouseOrderAuditUserId() == null) {
                purchaseWarehouseOrderDO.setWarehouseOrderAuditUserId(adminId);
                purchaseWarehouseOrderDO.setWarehouseOrderAuditTime(now);
                purchaseWarehouseOrderDO.setWarehouseOrderAuditRealname(adminDTO.getRealname());
            }
        }
        //修改入库单审批状态
        if (purchaseWarehouseOrderMapper.updateById(purchaseWarehouseOrderDO) > 0) {
            if (isPassed) {//通过
                WarehouseDO warehouseDO = warehouseMapper.selectById(purchaseWarehouseOrderDO.getWarehouseId());
                List<PurchaseWarehouseOrderGoodsDO> purchaseWarehouseOrderGoodsDOS = purchaseWarehouseOrderGoodsMapper.selectList(new EntityWrapper<PurchaseWarehouseOrderGoodsDO>()
                        .eq("warehouse_order_id", purchaseWarehouseOrderDO.getId())
                        .eq("warehouse_id", purchaseWarehouseOrderDO.getWarehouseId()));
                //通用仓库预警
                Float alarm = configBizService.getCommonGoodsAlarm();
                for (PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO : purchaseWarehouseOrderGoodsDOS) {
                    auditSku(purchaseWarehouseOrderDO,
                            purchaseWarehouseOrderGoodsDO,
                            warehouseDO,
                            adminId,
                            adminDTO,
                            alarm);
                }

                //插入应付记录
                FinancePayableDO financePayableDO = new FinancePayableDO();
                financePayableDO.setGmtUpdate(now);
                financePayableDO.setAdminId(adminId);
                financePayableDO.setAdminName(adminDTO.getRealname());
                financePayableDO.setFinishAmount(0);
                financePayableDO.setAddTime(purchaseWarehouseOrderDO.getWarehouseOrderAuditTime());
                financePayableDO.setPaymentCode("");
                financePayableDO.setSupplierId(purchaseWarehouseOrderDO.getSupplierId());
                financePayableDO.setPaymentYouhuiAmount(purchaseWarehouseOrderDO.getWarehouseOrderConpon());
                financePayableDO.setSupplierName(purchaseWarehouseOrderDO.getSupplierName());
                financePayableDO.setWarehouseOrderId(purchaseWarehouseOrderDO.getId());
                financePayableDO.setWarehouseOrderNo(purchaseWarehouseOrderDO.getWarehouseOrderNo());
                financePayableDO.setPaymentAllAmount(purchaseWarehouseOrderDO.getWarehouseOrderGoodsAmount().intValue());
                financePayableDO.setPaymentAmount(purchaseWarehouseOrderDO.getWarehouseOrderAmount().intValue());
                financePayableDO.setWarehouseId(purchaseWarehouseOrderDO.getWarehouseId());
                financePayableMapper.insert(financePayableDO);


            }
            //插入操作表
            //操作人真实姓名
            if (adminDTO != null) {
                insertPurchaseWarehouseOperLog(purchaseWarehouseOrderDO, adminDTO);
            }
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    /**
     * 插入操作日志 仓库-入库单
     *
     * @throws Exception
     */
    private void insertPurchaseWarehouseOperLog(PurchaseWarehouseOrderDO purchaseWarehouseOrderDO, AdminDTO adminDTO) {
        PurchaseWarehouseOperLogDO purchaseWarehouseOperLogDO = new PurchaseWarehouseOperLogDO();
        purchaseWarehouseOperLogDO.setPurcahseWarehouseOrderId(purchaseWarehouseOrderDO.getId());
        purchaseWarehouseOperLogDO.setGmtCreate(new Date());
        purchaseWarehouseOperLogDO.setOperUserId(adminDTO.getId());
        purchaseWarehouseOperLogDO.setOperUser(adminDTO.getRealname());
        purchaseWarehouseOperLogDO.setOperUserUsername(adminDTO.getUsername());
        purchaseWarehouseOperLogDO.setStatus(purchaseWarehouseOrderDO.getWarehouseOrderState());
        purchaseWarehouseOperLogMapper.insert(purchaseWarehouseOperLogDO);
    }

    /**
     *  确认主sku 入库
     * @param purchaseWarehouseOrderDO
     * @param purchaseWarehouseOrderGoodsDO
     * @param warehouseDO
     * @param adminId
     * @param adminDTO
     * @param alarm
     * @throws ServiceException
     */
    public void auditSku(PurchaseWarehouseOrderDO purchaseWarehouseOrderDO,
                               PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO,
                               WarehouseDO warehouseDO,
                               Long adminId,
                               AdminDTO adminDTO,
                               Float alarm) throws ServiceException {
        Date now = new Date();
        //更新库存商品数量
        List<WarehouseGoodsDO> warehouseGoodsDOS = warehouseGoodsMapper.selectList(new EntityWrapper<WarehouseGoodsDO>()
                .eq("warehouse_id", purchaseWarehouseOrderDO.getWarehouseId())
                .eq("sku_id", purchaseWarehouseOrderGoodsDO.getSkuId()));
        if(warehouseGoodsDOS == null || warehouseGoodsDOS.size() < 1){
            throw new AdminServiceException(ExceptionDefinition.MORE_UNIT_MASTER_NOT_FOUND);
        }
        WarehouseGoodsDO warehouseGoodsDO = null;
        WarehouseGoodsDO origWarehouseGoodsDO = null;
        Float changeSkuStock = purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum();
        Float totalSkuStock = 0.00f;
        if(CollectionUtils.isEmpty(warehouseGoodsDOS)){
            throw new AdminServiceException(ExceptionDefinition.MORE_UNIT_MASTER_NOT_FOUND);
        }
        if (!CollectionUtils.isEmpty(warehouseGoodsDOS)) {
            warehouseGoodsDO = warehouseGoodsDOS.get(0);
            origWarehouseGoodsDO = new WarehouseGoodsDO();
            BeanUtils.copyProperties(warehouseGoodsDO,origWarehouseGoodsDO);
            if (warehouseGoodsDO != null) {
                Float warehouseSkuStock = warehouseGoodsDO.getWarehouseSkuStock();
                warehouseSkuStock = warehouseSkuStock == null || "".equals(warehouseGoodsDO) ? 0 : warehouseSkuStock;
                totalSkuStock = warehouseSkuStock + changeSkuStock;
                warehouseGoodsDO.setWarehouseSkuStock(totalSkuStock);
                warehouseGoodsDO.setAllprice((long) (purchaseWarehouseOrderGoodsDO.getWarehouseGoodsAmount()) + warehouseGoodsDO.getAllprice());
                warehouseGoodsDO.setPrice(getCurrentPrice(origWarehouseGoodsDO,warehouseGoodsDO,purchaseWarehouseOrderGoodsDO));
                warehouseGoodsDO.setSkuId(purchaseWarehouseOrderGoodsDO.getSkuId());
                warehouseGoodsDO.setGmtUpdate(now);
                Float goodsHistoryAmount = warehouseGoodsDO.getGoodsHistoryAmount() == null ? 0L : warehouseGoodsDO.getGoodsHistoryAmount();
                warehouseGoodsDO.setGoodsHistoryAmount(goodsHistoryAmount + changeSkuStock);
                warehouseGoodsDO.setWarehouseName(warehouseDO.getWarehouseName());
                warehouseGoodsMapper.updateById(warehouseGoodsDO);
            }
        }
        //更新仓库-商品操作
        WarehouseOperLogDO warehouseOperLogDO = new WarehouseOperLogDO();
        warehouseOperLogDO.setGmtCreate(now);
        warehouseOperLogDO.setGmtUpdate(now);
        warehouseOperLogDO.setChangeSkuStock(purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum());
        warehouseOperLogDO.setAdminId(adminId);
        warehouseOperLogDO.setSkuId(purchaseWarehouseOrderGoodsDO.getSkuId());
        warehouseOperLogDO.setGmtUpdate(now);
        warehouseOperLogDO.setType(1);//1代表入库
        warehouseOperLogDO.setChangeSkuStock(changeSkuStock);
        warehouseOperLogDO.setWarehouseSkuStock(totalSkuStock);
        warehouseOperLogDO.setWarehouseId(purchaseWarehouseOrderGoodsDO.getWarehouseId());
        warehouseOperLogDO.setWarehouseName(warehouseDO.getWarehouseName());
        warehouseOperLogDO.setSkuNo(purchaseWarehouseOrderGoodsDO.getGoodsBarCode());
        warehouseOperLogDO.setOrderNo(purchaseWarehouseOrderDO.getWarehouseOrderNo());
        warehouseOperLogDO.setOrderId(purchaseWarehouseOrderGoodsDO.getWarehouseOrderId());
        warehouseOperLogDO.setAdminName(adminDTO.getRealname());
        warehouseOperLogDO.setSkuName(purchaseWarehouseOrderGoodsDO.getSkuName());
        warehouseOperLogDO.setSkuId(purchaseWarehouseOrderGoodsDO.getSkuId());
        warehouseOperLogDO.setSpuId(purchaseWarehouseOrderGoodsDO.getGoodsId());
        warehouseOperLogDO.setSpuName(purchaseWarehouseOrderGoodsDO.getSpuName());
        //补充字段
        warehouseOperLogDO.setOrigSkuStock(0f);
        warehouseOperLogDO.setOrigAvgPrice(0);
        if(origWarehouseGoodsDO != null){
            if(origWarehouseGoodsDO.getWarehouseSkuStock() != null){
                warehouseOperLogDO.setOrigSkuStock(origWarehouseGoodsDO.getWarehouseSkuStock());
            }
        }
        if(origWarehouseGoodsDO != null){
            if(origWarehouseGoodsDO.getPrice() != null){
                warehouseOperLogDO.setOrigAvgPrice(origWarehouseGoodsDO.getPrice().intValue());
            }
        }
        warehouseOperLogDO.setCurrAvgPrice(warehouseGoodsDO.getPrice().intValue());
        warehouseOperLogMapper.insert(warehouseOperLogDO);
        //总库变化
       // goodsBizService.updateGoodsStockByPara(purchaseWarehouseOrderGoodsDO.getSkuId(), purchaseWarehouseOrderGoodsDO.getGoodsBarCode(), GoodsEntryType.PURCHASE.getCode(), purchaseWarehouseOrderGoodsDO.getWarehouseGoodsBuyNum());
    }


    /**
     *
     * @param origWarehouseGoodsDO
     * @param warehouseGoodsDO
     * @param purchaseWarehouseOrderGoodsDO
     * @return
     */
    public Long getCurrentPrice(WarehouseGoodsDO origWarehouseGoodsDO,WarehouseGoodsDO warehouseGoodsDO,PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO){
        //入库前平均价
        Long price = warehouseGoodsDO.getPrice();
        //入库前库房单品成本
        Double origCost = MoneyUtils.mul(origWarehouseGoodsDO.getWarehouseSkuStock().doubleValue(), price.doubleValue());
        //入库总价
        Long warehouseGoodsAmount = purchaseWarehouseOrderGoodsDO.getWarehouseGoodsAmount();
        //入库后总成本
        Double currCost = MoneyUtils.add(origCost, warehouseGoodsAmount.doubleValue());
        //入库后总库存
        Double currStock = warehouseGoodsDO.getWarehouseSkuStock().doubleValue();
        //最新平均价
        Double avgPrice = MoneyUtils.div(currCost, currStock);
        return avgPrice.longValue();
    }
}